const debug = require('debug')('build:plugins/svg2font');
const WebpackIconfontPluginNodejs = require('webpack-iconfont-plugin-nodejs');
const path = require('path');
const file = require('@colpu/core/src/utils/file');
class SVGIconFont extends WebpackIconfontPluginNodejs {
  constructor(options = {}) {
    const root = options.root || path.resolve('src/static/') + '/';
    delete options.root;
    const fontName = options.fontName || 'iconfont';
    const fontDirName = options.fontDirName || 'fonts';
    const fontFileName = path.join(root, fontDirName, fontName);
    const svgsDir = `${root}svg/`;
    options = Object.assign({
      fontName,
      svgs: `${svgsDir}*.svg`,
      fontsOutput: `${root}${fontDirName}`,
      cssOutput: `${fontFileName}.css`,
      jsOutput: `${fontFileName}.js`,
      htmlOutput: `${root}${fontDirName}/${fontName}_preview.html`,
      cssPrefix: 'ift'
    }, options);
    debug('判断是否存在目录 %s', file.existsSync(svgsDir));
    super(options);
    this.root = root;
    this.options = options;
    this.svgsDir = svgsDir;
  }
  build(callback) {
    const {
      root,
      svgsDir
    } = this;
    if (!file.existsSync(svgsDir)) {
      return '';
    }
    const {
      cssOutput,
      fontName
    } = this.options;

    callback = callback || function build() {
      debug('svg build %s', file.existsSync(svgsDir));
      let content = file.readFileSync(cssOutput);
      const reg = new RegExp(`(${fontName}\\.)`, 'g');
      content = content.toString().replace(reg, '#{$staticRoot}fonts/$1');
      file.writeFileSync(`${root}fonts/${fontName}.scss`, content);
    };
    return super.build(callback);
  }
}

module.exports = SVGIconFont;
